<template>
  <div class="">
    <div class="c-p" v-if="showDesc && upAgent && upAgent.recruitDesc && applyPageInfo">
      <div class="tinymce-text c-lh36 c-fc-sblack c-ww-bw c-ww-ba c-bg-xblue" :style="{'background-color': upAgent.backcolor, 'padding': '0 '+upAgent.margin+'px'}" v-html="upAgent.recruitDesc"></div>
      <div class="c-bd-t1 c-pf c-p-b0 c-w100 c-maxw640 c-bg-white c-pz100 c-ph24 c-flex-column c-justify-sa box-shadow" :class="protocolInfo ? '' : 'c-hh88'">
        <div class="c-pv28 c-fs22 c-lh36 c-flex-row" @click="isCheckAgreement = !isCheckAgreement" v-if="protocolInfo">
          <div class="iconfont">{{isCheckAgreement ? '&#xe6f2;' : '&#xe6f7;'}}</div>
          <span class="c-pl16">我已阅读并同意以上规则以及 <span class="theme-fc" @click.stop="clickProtocol(item)" v-for="(item, index) in protocolInfo" :key="index">《{{item.name}}》</span></span>
        </div>
        <div :class="protocolInfo ? 'c-hh88' : ''">
          <div @click="changeOpenAgent" :class="canApply ? 'theme-bg' : 'c-bg-ccc'" class="c-fc-white c-br36 c-textAlign-c c-hh64 c-ph10 c-fs26 c-lh64">申请创建权限</div>
        </div>
      </div>
    </div>
    <template v-if="!showDesc">
      <div class="">
        <header class="agentBg c-w100 c-hh140 c-fs28 c-p">
          <div class="c-pv50 c-fc-white c-textAlign-c">请填写如下信息，方便商家审核</div>
          <!-- <div class="theme-bg c-fc-white c-fs20 c-ww120 c-hh40 c-flex-row c-flex-center c-br-tl20 c-br-bl20 c-pa c-p-r0 c-p-t20" @click="goAgentInfo()">权益说明</div> -->
        </header>
        <div>
          <div class="c-bg-white c-mt10">
            <div class="c-fs24 c-lh34 c-fc-sblack c-pv28 c-bd-b1 c-flex-row c-justify-sb c-aligni-center c-mh24">
              <div class="c-ws-n">昵称:</div>
              <div class=""><input type="text" readonly v-model="name" placeholder="请输入昵称" class="c-textAlign-r c-fs24 c-bd0 input c-fc-gray" /></div>
            </div>
            <!-- <div class="c-fs24 c-lh34 c-fc-sblack c-pv28 c-bd-b1 c-w100 c-flex-row c-aligni-center">
              <div class="c-ws-n c-ww130"><span class="c-fc-xmlred c-pr5">*</span>真实姓名</div>
              <div class="c-flex-row c-justify-end c-flex-1"><input type="text" maxlength="10" v-model="realName" placeholder="请输入真实姓名" class="c-textAlign-r c-fs24 c-bd0 input c-w80" :class="realName == '' ? 'c-fc-gray' : 'c-fc-xblack'" /></div>
            </div> -->
            <div class="c-bg-sgray" v-if="formData && formData.length">
              <activity-enroll-form :enableCustomerForm="true" :formData="formData" :isCollectForm="0" :isFromPromotedAccount="true" :promotedAccountStatus="promotedAccountStatus" :originMobile="applyPageInfo.userInfo ? Number(applyPageInfo.userInfo.mobile) : 0" @submit="submitForm"></activity-enroll-form>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import ActivityEnrollForm from "@/components/templates/activity/activityEnrollForm.vue";
export default {
  name: "PromotedAccountIndex",
  components: {
    ActivityEnrollForm
  },
  props: [],
  beforeCreate() { },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      name: "", // 姓名
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      // 自定义服务商名称
      ckFrom: global.ckFrom,
      isLoading: false,
      upAgent: null,
      // showAllContent: false, //招募信息是否全部展示
      protocolInfo: null, // 协议信息
      isCheckAgreement: false, // 是否勾选协议
      formData: [],
      promotedAccountStatus: 1, //1：未提交（或者审核不通过） 2：审核中 3:审核失败 4:已通过
      applyPageInfo: '',
      showDesc: true,
      canApply: true //是否可以申请
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {
  },
  watch: {
  },
  methods: {
    submitForm(fData) {
      if (this.isClick)
        return;
      this.isClick = true;
      let upAccountType = '';
      if (fData[0].fieldVal && fData[0].fieldVal.length > 0) {
        let accountTypeItem = fData[0].fieldVal.filter(item => {
          return item.dataType == 999;
        })
        if (accountTypeItem.length > 0) {
          upAccountType = accountTypeItem[0].value[0] == "高级子店铺" ? 1 : 2;
        }
        fData[0].fieldVal = fData[0].fieldVal.filter(item => {
          return item.dataType != 999;
        })
      }
      let data = {
        nickname: this.name,
        formContent: fData[0].fieldVal
      }
      data.upAccountType = upAccountType;
      if (fData[0].code) {
        data.code = fData[0].code;
      }
      data.mobile = fData[0].mobile;
      utilJs.postMethod(global.apiurl + 'promotedAccount/saveApplyLog', data, res => {
        this.$showCjToast({
          text: `已提交审核`,
          type: "success",
        });
        this.promotedAccountStatus = 2;
        this.isClick = false;
      }, failres => {
        this.isClick = false;
      });
    },
    //服务上等级名称
    getApplyPage() {
      let url = 'promotedAccount/applyPage';
      utilJs.getMethod(global.apiurl + url, res => {
        // this.formData = res.form;
        if (res.config.enablePromotedAccount == 0) {
          let that = this;
          this.$showCjToast({
            text: "没有开通子店铺",
            type: "warn",
          }).then(() => {
            that.$routerGo(that, "replace", { path: "/member/memberIndex" });
          });
          return;
        }
        if ((res.config.allowApplyUserType == 2 && res.userInfo.vipType == 1) || (res.config.allowApplyUserType == 3 && (res.userInfo.vipType == 1 || res.userInfo.vipType == 2 || res.userInfo.vipType == 4))) {
          // let that = this;
          // this.$showCjToast({
          //   text: "没有开通推广账号",
          //   type: "warn",
          //   time: 1000,
          //   onHide() {
          //     that.$routerGo(that, "replace", { path: "/member/memberIndex" });
          //   }
          // });
          this.canApply = false; //身份不符合申请要求
        }
        if (res.userMiniPage.code == 3) {
          this.$routerGo(this, "replace", {
            path: `/error/emptyPage?info=请在商家后台创建微页面`
          });
          return;
        }
        if (res.userMiniPage.code == 0 && res.userMiniPage.url) {
          window.location.replace(res.userMiniPage.url);
          return;
        }
        this.applyPageInfo = res;
        let accountType = [{ //选择子店铺类型必须有
          dataType: 999,
          enabled: 1,
          isMultiline: 1,
          isReq: 1,
          isSystemField: 0,
          name: "子店铺类型",
          options: null,
          placeholder: "请选择子店铺类型",
          value: res.apply && res.apply.upAccountType == 1 ? ['高级子店铺'] : res.apply && res.apply.upAccountType == 2 ? ['普通子店铺'] : ''
        }]
        if (res.apply) {
          // this.$set(this.upAgent, 'isOpenJoinAgent', 0)
          if (res.apply.auditStatus == -1) {
            this.promotedAccountStatus = 3;
            this.formData.push({
              fieldVal: [...res.form, ...accountType]
            })
          } else if (res.apply.auditStatus == 2) { //已审核通过
            this.showDesc = false;
            this.promotedAccountStatus = 4;
            this.formData.push({
              fieldVal: [...res.apply.formContent, ...accountType]
            })
          } else {
            this.showDesc = false;
            this.promotedAccountStatus = 2;
            this.formData.push({
              fieldVal: [...res.apply.formContent, ...accountType]
            })
          }
          this.name = res.apply.nickname;
        } else {
          this.formData.push({
            fieldVal: [...res.form, ...accountType]
          })
          this.name = res.userInfo.nickname;
        }
        if (this.showDesc) {
          setDocumentTitle(this.upAgent && this.upAgent.recruitName ? this.upAgent.recruitName : "子店铺招募计划");// eslint-disable-line
        } else {
          setDocumentTitle("子店铺招募计划");// eslint-disable-line
        }
      });
    },
    changeOpenAgent() {
      if (!this.canApply) {
        return;
      }
      if (this.protocolInfo && this.isCheckAgreement == false) {
        this.$showCjToast({
          text: '请勾选协议',
          type: 'warn'
        });
        return;
      }
      this.showDesc = false;
    },
    clickProtocol(item) {
      this.$routerGo(this, "push", { path: `/homePage/agent/protocolInfo`, query: { protocolId: item.protocolId } });
    },
    //分享
    wechatShare: function () {
      let title = '子店铺招募计划';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.upAgent && this.upAgent.recruitShareDesc && this.applyPageInfo && this.applyPageInfo.userMiniPage.code == 1 ? this.upAgent.recruitShareDesc : "快来一起加入创业计划";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      let title = '子店铺招募计划';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.upAgent && this.upAgent.recruitShareDesc && this.applyPageInfo && this.applyPageInfo.userMiniPage.code == 1 ? this.upAgent.recruitShareDesc : "快来一起加入创业计划";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
  activated() {
    this.isLoading = false;
    // this.showAllContent = false;
    this.isCheckAgreement = false;
    this.protocolInfo = null;
    utilJs.getMethod(`${global.apiurl}protocols/getProtocolByProdType?prodType=400`, (res) => {
      this.protocolInfo = res.protocol && res.protocol.length > 0 ? res.protocol : null;
    });
    this.formData = [];
    this.promotedAccountStatus = 1;
    this.applyPageInfo = "";
    this.showDesc = true;
    this.canApply = true;
    let url = 'promotedAccount/promotedAccountRecruit';
    utilJs.getMethod(`${global.apiurl}${url}`, res => {
      this.getApplyPage();
      this.upAgent = res;
      let recruitDesc = res.recruitDesc;
      if (recruitDesc && recruitDesc.substring(0, 4) == 'http' && recruitDesc.length > 5) {
        this.upAgent.recruitDesc = "";
        utilJs.getPageHtml(recruitDesc, sres => {
          for (let i = 0; i < res.replaceInfo.length; i++) {
            if (res.replaceInfo[i].replaceKey) {
              sres = sres.replace(new RegExp(res.replaceInfo[i].replaceKey, "gm"), res.replaceInfo[i].replaceValue);
            }
          }
          this.upAgent.recruitDesc = sres;
        });
      }
      // setDocumentTitle("子店铺招募计划");// eslint-disable-line
      // if (!(res.isAgent == 0 && res.isOpenJoinAgent == 1 && res.isApply == 0 && res.isFinish == 0)) {
      // this.getApplyPage();
      // }
      setTimeout(() => {
        this.wechatShare();
      }, 500);
    }, failRes => {
      this.wechatShare();
    });
  },
  deactivated() {
    clearInterval(this.interval);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.vux-cell-box:not(:first-child):before {
  border-top: none !important;
}
.base-red {
  color: #fa5e45;
}
.Quota-blue {
  color: #56adff;
}
.redeem-orange {
  color: #ff8237;
}
.present-orange {
  color: #5a80f8;
}
.quota-cost {
  color: #00d493;
}
::-webkit-input-placeholder {
  /* WebKit browsers */
  color: #999;
  font-size: 0.6rem;
  line-height: 0.85rem;
}
::-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #999;
}
::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #999;
}
::-ms-input-placeholder {
  /* Internet Explorer 10+ */
  color: #999;
}
.agentBg {
  background-image: url('../../../assets/i/wap/newAreaAgent/agentBg.jpg');
  background-size: contain;
}
.result >>> .vux-cell-value {
  color:#333333 !important;
}
.box-shadow {box-shadow: 8px 5px 6px 10px rgba(0, 0, 0, 0.1)}
</style>
